﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel;
using System.Data.SqlClient;
using EFDataBase.Models;
using System.IO;
using System.Runtime.Serialization;
namespace EFDataBase
{
    public class ShowProduct
    {
        /// <summary>
        /// 获取商品
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public DataTable GetProduct(string where)
        {
            string sql = "";
            string dbstr = System.Configuration.ConfigurationManager.AppSettings["DBString"].ToString();
            SqlConnection conn = new SqlConnection(dbstr);
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            conn.Close();
            return ds.Tables[0];

        }
        public List<View_product> GetProduct<T>(string where, string data)
        {

            using (YiDaShuiHangsContext con = new YiDaShuiHangsContext())
            {
                IList<View_product> product = con.View_product.Where(b => b.deletes == "1"
                    &&b.productset.Contains(where)).ToList<View_product>();
               
                return (List<View_product>)product;
            }


        }
        public string JsonData(string where) {
            List<View_product> list = GetProduct<View_product>(where, "");
            //if (list.Count == 0)
            //    return "";
            //else
            return ObjToJson<List<View_product>>(list);
        }
        public static string ObjToJson<T>(T data)
        {
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, data);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch
            {
                return null;
            }
        }
    }
}

